var KV = require("./kvParser")

const fs = require('fs')



var fromFileDesc = "dota_schinese.txt"
var toFileDesc = "addon_schinese.txt"

var heroList=[
	"npc_dota_hero_abaddon",
	"npc_dota_hero_alchemist",
	"npc_dota_hero_ancient_apparition",
	"npc_dota_hero_antimage",
	"npc_dota_hero_axe",
	"npc_dota_hero_bane",
	"npc_dota_hero_batrider",
	"npc_dota_hero_beastmaster",
	"npc_dota_hero_bloodseeker",
	"npc_dota_hero_bounty_hunter",
	"npc_dota_hero_brewmaster",
	"npc_dota_hero_bristleback",
	"npc_dota_hero_broodmother",
	"npc_dota_hero_centaur",
	"npc_dota_hero_chaos_knight",
	"npc_dota_hero_chen",
	"npc_dota_hero_clinkz",
	"npc_dota_hero_crystal_maiden",
	"npc_dota_hero_dark_seer",
	"npc_dota_hero_dazzle",
	"npc_dota_hero_death_prophet",
	"npc_dota_hero_disruptor",
	"npc_dota_hero_doom_bringer",
	"npc_dota_hero_dragon_knight",
	"npc_dota_hero_drow_ranger",
	"npc_dota_hero_earth_spirit",
	"npc_dota_hero_earthshaker",
	"npc_dota_hero_elder_titan",
	"npc_dota_hero_ember_spirit",
	"npc_dota_hero_enchantress",
	"npc_dota_hero_enigma",
	"npc_dota_hero_faceless_void",
	"npc_dota_hero_furion",
	"npc_dota_hero_gyrocopter",
	"npc_dota_hero_huskar",
	"npc_dota_hero_invoker",
	"npc_dota_hero_jakiro",
	"npc_dota_hero_juggernaut",
	"npc_dota_hero_keeper_of_the_light",
	"npc_dota_hero_kunkka",
	"npc_dota_hero_legion_commander",
	"npc_dota_hero_leshrac",
	"npc_dota_hero_lich",
	"npc_dota_hero_life_stealer",
	"npc_dota_hero_lina",
	"npc_dota_hero_lion",
	"npc_dota_hero_lone_druid",
	"npc_dota_hero_luna",
	"npc_dota_hero_lycan",
	"npc_dota_hero_magnataur",
	"npc_dota_hero_medusa",
	"npc_dota_hero_meepo",
	"npc_dota_hero_mirana",
	"npc_dota_hero_morphling",
	"npc_dota_hero_naga_siren",
	"npc_dota_hero_necrolyte",
	"npc_dota_hero_nevermore",
	"npc_dota_hero_night_stalker",
	"npc_dota_hero_nyx_assassin",
	"npc_dota_hero_obsidian_destroyer",
	"npc_dota_hero_ogre_magi",
	"npc_dota_hero_omniknight",
	"npc_dota_hero_phantom_assassin",
	"npc_dota_hero_phantom_lancer",
	"npc_dota_hero_phoenix",
	"npc_dota_hero_puck",
	"npc_dota_hero_pudge",
	"npc_dota_hero_pugna",
	"npc_dota_hero_queenofpain",
	"npc_dota_hero_rattletrap",
	"npc_dota_hero_razor",
	"npc_dota_hero_riki",
	"npc_dota_hero_rubick",
	"npc_dota_hero_sand_king",
	"npc_dota_hero_shadow_demon",
	"npc_dota_hero_shadow_shaman",
	"npc_dota_hero_shredder",
	"npc_dota_hero_silencer",
	"npc_dota_hero_skeleton_king",
	"npc_dota_hero_skywrath_mage",
	"npc_dota_hero_slardar",
	"npc_dota_hero_slark",
	"npc_dota_hero_sniper",
	"npc_dota_hero_spectre",
	"npc_dota_hero_spirit_breaker",
	"npc_dota_hero_storm_spirit",
	"npc_dota_hero_sven",
	"npc_dota_hero_templar_assassin",
	"npc_dota_hero_terrorblade",
	"npc_dota_hero_tidehunter",
	"npc_dota_hero_tinker",
	"npc_dota_hero_tiny",
	"npc_dota_hero_treant",
	"npc_dota_hero_troll_warlord",
	"npc_dota_hero_tusk",
	"npc_dota_hero_undying",
	"npc_dota_hero_ursa",
	"npc_dota_hero_vengefulspirit",
	"npc_dota_hero_venomancer",
	"npc_dota_hero_viper",
	"npc_dota_hero_visage",
	"npc_dota_hero_warlock",
	"npc_dota_hero_weaver",
	"npc_dota_hero_windrunner",
	"npc_dota_hero_wisp",
	"npc_dota_hero_witch_doctor",
	"npc_dota_hero_zuus",
]
var abilityCopyKeys=[
	"AbilitySpecial",
	// "AbilityCastRange",
	// "AbilityCastPoint",
	// "AbilityCooldown",
	// "AbilityDamage",
	"AbilityManaCost",
	"MaxLevel",
	// "AbilityCastRangeBuffer"
]

Array.prototype.contains = function(item){
	    var flag =false;
	    for(index in this){
	        flag = (item==this[index])?true:false;
	        if(flag)break;
	    }
	    return flag;
	}

 var npcAbilitiesFile="npc_abilities.txt"
startCopyNpcAbilities(npcAbilitiesFile,"ability1.txt")

// startCopyDesc(fromFileDesc, toFileDesc, abilityNameList, modifierNameList)
// startCopyAbility("ability.txt")
var curAbilityName=""
 

function startCopyNpcAbilities(fromFile,toFile){
	var encoding = "ascii"
	let buf = fs.readFileSync(fromFile, encoding);
	var kvData = KV.parse(buf, 0).kv;
	if (kvData.key !== "DOTAAbilities") {
		console.error("DOTAAbilities  not found!!!!")
		return
	}
	var rootData= new KV()
	rootData.key="DOTAAbilities"
	rootData.value=[]
	for(var i=0;i<kvData.value.length;i++){
		if(heroList.contains("npc_dota_hero_"+kvData.value[i].key.split("_")[0])){
			var isUltimate=false;
			kvData.value[i].value.map(function(v){
				if(v.key==="AbilityType"&&v.value==="DOTA_ABILITY_TYPE_ULTIMATE"){
					isUltimate=true;
				}
			})
			var newData=new KV()
			newData.key=kvData.value[i].key
			newData.value=[]
			curAbilityName=newData.key

			kvData.value[i].value.map(function(v){
				if(abilityCopyKeys.contains(v.key)){
					var numCount=9
					if(isUltimate){
						numCount=7
					}
					//  console.log(typeof(v.value))
					 switch(v.key){
						 case "AbilityType":
							 break;
						default:
								if(typeof(v.value)==="object"){
									v.value.map(function(spKV){
									   spKV.value.map(function(spKVV){
										   if(spKVV.key!=="var_type"){
											   var numValues= spKVV.value.split(" ")
											   if(isNaN(numValues[0])===false){
												   // console.log(Number(numValues[0]))
												   spKVV.value=pushAbilityLevelConfig(spKVV.key,numCount,spKVV.value)
											   }
										   }
									   })
									})
								}
								else if(typeof(v.value)==="string"){
								   v.value= pushAbilityLevelConfig(v.key,numCount,v.value)
								}
								else{
									console.error("not type match")
								}

							break;
					 }
					 newData.value.push(v)
				 
				}
			})
			rootData.value.push(newData)
		}
	}
	fs.writeFileSync(toFile, rootData.toString())
}

function pushAbilityLevelConfig(key,count,value){
	var numValues=value.split(" ");
	//  console.log(numValues)
	var numValuesStr=""
	for(var z=0;z<(numValues.length);z++){
		if("AbilityManaCost"==key){
			numValuesStr=numValuesStr+Math.round(Number(numValues[z])/4)+" "
		}
		else if("damage"==key&&curAbilityName=="rattletrap_battery_assault"){
			numValuesStr=numValuesStr+Math.round(Number(numValues[z])/2)+" "
		}
		else{
			numValuesStr=numValuesStr+(Number(numValues[z]))+" "
		}
 
	}
	numValuesStr=numValuesStr.substr(0,numValuesStr.length-1)
	return numValuesStr
}

function startCopyAbility(fromFile){
	createNewAbilityFile(fromFile,2)
	createNewAbilityFile(fromFile,3)

}
 
 

function createNewAbilityFile(fromFile,num){
	var encoding = "ascii"
	let buf = fs.readFileSync(fromFile, encoding);
	var kvData = KV.parse(buf, 0).kv;
	var toFile1=fromFile.replace(".txt",num+".txt")
	// console.log(kvData)
	if (kvData.key !== "DOTAAbilities") {
		console.error("DOTAAbilities  not found!!!!")
		return
	}
	for(var i=0;i<kvData.value.length;i++){
		kvData.value[i].key=kvData.value[i].key.replace("_1","_"+num)
		var subLevelValue=null
		for(var j=0;j<kvData.value[i].value.length;j++){
			if (kvData.value[i].value[j].key==="AbilitySpecial"){
				// console.log(kvData.value[i].value[j])
				var l1=kvData.value[i].value[j].value.length-1;
				var l2=kvData.value[i].value[j].value[l1].value.length-1
				if(kvData.value[i].value[j].value[l1].value[l2].key==="ability_sub_level"){
					kvData.value[i].value[j].value[l1].value[l2].value=String(num)
				}
				// console.log( kvData.value[i].value[j].value[l1].value[l2])
			}
		}
	}
	fs.writeFileSync(toFile1, kvData.toString())
}



function startCopyDesc(fromFile, toFile, abilityList, modifierList) {
	var encoding="ucs2"
	let buf = fs.readFileSync(fromFile, encoding);
	let bufTo = fs.readFileSync(toFile, encoding);
	var kvData = KV.parse(buf, 0);
	var kvDataTo = KV.parse(bufTo, 0)
	var tokens = kvData.kv.value[1]
	var tokensTo = kvDataTo.kv.value[1]
	var abilityPrefix = "DOTA_Tooltip_ability_"
	var modifierPrefix = "DOTA_Tooltip_modifier_"

	if (tokens.key !== "Tokens" || tokensTo.key !== "Tokens") {
		console.error("tokens  not found!!!!")
		return
	}
	var abilityContent = []
	var modifierContent = []
	tokens.value.map(function (v) {
		var hasSameKey = false;
		for (var i = 0; i < abilityList.length; i++) {
			if (v.key.toLowerCase().indexOf((abilityPrefix + abilityList[i]).toLowerCase()) !== -1) {
				abilityContent.push({
					abilityName: abilityList[i],
					key: v.key,
					value: v.value
				})
				hasSameKey = true
				break;
			}
		}
		if (hasSameKey !== true) {
			for (var j = 0; j < modifierList.length; j++) {
				if (v.key.toLowerCase().indexOf((modifierPrefix + modifierList[j]).toLowerCase()) !== -1) {
					modifierContent.push({
						modifierName: modifierList[j],
						key: v.key,
						value: v.value
					})
					hasSameKey = true
					break;
				}
			}
		}
	})
	for (var i = 1; i <= 3; i++) {
		abilityContent.map(function (w) {
			tokensTo.set(w.key.replace(w.abilityName, w.abilityName + "_" + i), w.value)
		})
	}
	modifierContent.map(function (w) {
		tokensTo.set(w.key.replace(w.modifierName, w.modifierName + "_datadriven"), w.value)
	})
	fs.writeFile(toFileDesc, kvDataTo.kv.toString(), function (err) {
		if (err) {
			console.error("write..error");
		} else {
			console.log("success..");
		}
	});

}

